package com.ycode.bang.anbang.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.adapter.PersonaOrderAdapter;
import com.ycode.bang.anbang.baseui.BaseFragment;
import com.ycode.bang.anbang.model.Order;
import com.ycode.bang.anbang.network.FinalHttpUtil;
import com.ycode.bang.anbang.refresh.SwipeRefreshLayout;
import com.ycode.bang.anbang.utils.RequestMapDev;
import com.ycode.bang.anbang.utils.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

/**
 * Created by maosongsong on 2016/4/6.
 */
public class AdviceNewFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener {
    public static final String TAG = "WaitHandleFragment";
    View view = null;
    @InjectView(R.id.list_event)
    RecyclerView mRecyclerView;
    // 下拉刷新，上拉加载
    @InjectView(R.id.swipe_container)
    public SwipeRefreshLayout mSwipeLayout;
    private PersonaOrderAdapter eventAdapter = null;
    private int mPageNum = 1;
    private int mPageMax = 1;
    private final int limmit =10;

    private List<Order> mList = new ArrayList<>();

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情，这里再次调用此Runnable对象，以实现每1秒实现一次的定时器操作
//            handler.postDelayed(this, 1500);

            if (mSwipeLayout != null) {
                mSwipeLayout.setRefreshing(false);
            }
            if (mSwipeLayout != null) {
                mSwipeLayout.setLoading(false);
            }
            // mListAdapter.notifyDataSetChanged();

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
    Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_public_new_handle, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
//        initData();
        initAction();
    }


    @Override
    protected void onVisible() {
        mPageNum=1;
        initData();
    }

    private void initView() {
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list_event);
    }

    private void initData() {
        getList();
//        List<Order> mList = new ArrayList<>();
//        eventAdapter = new PersonaOrderAdapter(getActivity(), mList,1,4);
    }

    private void initAction() {
        initSwipe();
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(
                getActivity(), LinearLayoutManager.VERTICAL, false));
        eventAdapter=new  PersonaOrderAdapter(getActivity(), mList,1,4);
        mRecyclerView.setAdapter(eventAdapter);
    }

    /**
     * 初始化Swipe
     */
    private void initSwipe() {
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setOnLoadListener(this);
        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeLayout.setLoadNoFull(true);//是否需要上拉加载
    }

    //关闭刷新
    private void closeSwipe() {
        if (mSwipeLayout != null) {
            mSwipeLayout.setLoading(false);
            mSwipeLayout.setRefreshing(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        onVisible();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }


    @Override
    public void onDestroyView() {
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
        super.onDestroyView();
    }

    @Override
    protected void getSuccessRequest(Object response, int flag) {
        closeSwipe();
    }


    @Override
    public void onLoad() {
        mPageMax++;
        mPageNum=mPageMax;
        handler.postDelayed(runnable, 1500);
        initData();
    }

    @Override
    public void onRefresh() {
        mPageNum = 1;
        mPageMax=1;
        handler.postDelayed(runnable, 1500);
        initData();
    }
    /**
     * 获取受理工单列表
     */
    private void getList() {
//        if (mPageMax!=0&&mPageNum!=1){
//            ToastUtil.show(getActivity(),R.string.no_more_info);
//        }
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("adviseType", "0");
        mAjaxParam.put("page",mPageNum+"");
        FinalHttpUtil.get(RequestMapDev.GetAdvList, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        List<Order> list;
                        list = gson.fromJson(data, new TypeToken<List<Order>>() {
                        }.getType());
                        if (list.size()==0){
                            mPageMax--;
                            if (mPageNum!=1)
                            ToastUtil.show(getActivity(),R.string.no_more_info);
                            return;
                        }
                        if (mPageNum==1)
                            mList.clear();
                        mList.addAll(list);
                        eventAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtil.show(getActivity(), msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(getActivity(), e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
//                ToastUtil.show(getActivity(), strMsg);
                if (mPageNum!=1&&mPageMax>1)
                    mPageMax--;

            }
        });
    }
}
